package cn.net.xyan.controller

import cn.net.xyan.kotlin.logger
import cn.net.xyan.pay.core.entity.VendorUserInfo
import cn.net.xyan.pay.core.service.VendorUserInfoProvider
import cn.net.xyan.pay.wechat.WeChatConfiguration
import me.chanjar.weixin.common.bean.WxJsapiSignature
import me.chanjar.weixin.mp.api.WxMpService
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.RequestMapping
import javax.servlet.http.HttpServletRequest

/**
 * Created by zarra on 2017/4/12.
 */

@Controller
class MPRootController{

    @Autowired
    lateinit var wxMpService: WxMpService

    @Autowired
    lateinit var vendorUserInfoProviders:List<VendorUserInfoProvider>

    @RequestMapping("page/page1")
    fun page(vendorUserInfo: VendorUserInfo,mm:ModelMap,httpRequest:HttpServletRequest):String{

        logger.info("-------------------------------------------------")
        if (httpRequest.parameterMap!=null)
            httpRequest.parameterMap.forEach { s, strings ->  logger.info("parameter $s = $strings")}

        logger.info("vendorUserInfo $vendorUserInfo")
//        val code = httpRequest.getParameter("code")
//
//        if (code != null){
//            val accessToken: WxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code)
//
//            mm.put("openID",accessToken.openId)
//        }
//
        val url = "http://wcloud.xyan.net.cn/mp/page"

        mm.put("appID",WeChatConfiguration.appID)
        mm.put("appSecret",WeChatConfiguration.appSecret)
        mm.put("token",WeChatConfiguration.token)
        mm.put("aesKey",WeChatConfiguration.aesKey)

        val signature: WxJsapiSignature = wxMpService.createJsapiSignature(url)

        mm.put("signature",signature)


        mm.put("vendorUserInfo",vendorUserInfo)

        logger.info("-------------------------------------------------")

        return "page1"
    }

    @RequestMapping("page/page2")
    fun page2(mm:ModelMap,httpRequest:HttpServletRequest):String{
        return "page2"
    }
}